const path = require("path");
const resolve = (dir) => path.join(__dirname, dir);
const webpack = require("webpack");
const vConsolePlugin = require("vconsole-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const compressionWebpackPlugin = require("compression-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
// const { JKBPVersionCheckPlugin } = require("jkbp-versionCheck-webpack-plugin");

function getBuildVersionByDateTime() {
  const newDate = new Date()
  return `${newDate.getFullYear()}.${newDate.getMonth() + 1}.${newDate.getDate()}-${newDate.getHours()}:${newDate.getMinutes()}`
}

module.exports = {
  publicPath: process.env.VUE_APP_PUBLIC_PATH,
  outputDir: process.env.VUE_APP_OUTPUT_DIR, // 打包输出不同的文件名
  // assetsDir: process.env.VUE_APP_ASSETS_DIR, // 打包输出静态文件名
  lintOnSave: true, // eslint-loader 是否在保存的时候检查
  runtimeCompiler: false,
  productionSourceMap: false, // 将其设置为 false 以加速生产环境构建
  pluginOptions: {
    // 第三方插件配置
    "style-resources-loader": {
      // 使用less全局变量
      preProcessor: "less",
      patterns: [path.resolve(__dirname, "./src/style")], // less所在文件路径
    },
  },
  configureWebpack: (config) => {
    // vconsole执行build:stage测试打包
    const envType = !["production", "development"].includes(
      process.env.NODE_ENV
    );
    const buildVersion = getBuildVersionByDateTime()
    const pluginsDev = [
      // new JKBPVersionCheckPlugin({
      //   queryUrl: 'http://jkbp.abc/devportal-api/devportal-service/ComponentResource/checkVersion'
      // }),
      new vConsolePlugin({
        filter: [],
        enable: envType,
      }),
      // 去除moment.js中非zh-cn的语言包
      new webpack.ContextReplacementPlugin(/moment[/\\]locale/, /zh-cn/),
      new webpack.DefinePlugin({
        process:{
          env:{
          BUILDVERSION:  JSON.stringify(buildVersion)
         }
       }
      })
    ];
    config.plugins.push(...pluginsDev);

    // 生产环境插件
    const pluginsPro = [
      new compressionWebpackPlugin({
        algorithm: "gzip",
        test: /\.js$|\.html$|\.css$/,
        threshold: 10240,
        deleteOriginalAssets: false,
      }),
    ];

    if (process.env.NODE_ANALYSE) {
      pluginsPro.push(new BundleAnalyzerPlugin());
    }

    if (process.env.NODE_ENV === "production") {
      config.plugins.push(...pluginsPro);
    }

    if (process.env.NODE_ENV !== "development") {
      // 为生产环境修改配置
      // 将每个依赖包打包成单独的js文件
      const optimization = {
        runtimeChunk: {
          name: (entrypoint) => `runtime-${entrypoint.name}`,
        },
        chunkIds: "named",
        flagIncludedChunks: true,
        occurrenceOrder: true,
        usedExports: true,
        sideEffects: true,
        concatenateModules: true,
        minimize: true,
        minimizer: [
          new TerserPlugin({
            parallel: true,
            extractComments: false,
            terserOptions: {
              compress: {
                drop_console: false,
                drop_debugger: true,
              },
              output: {
                comments: false,
              },
            },
          }),
          new CssMinimizerPlugin(),
        ],
        splitChunks: {
          chunks: "all",
          minChunks: 1,
          maxAsyncRequests: 30,
          maxInitialRequests: 30,
          enforceSizeThreshold: 50000,
          cacheGroups: {
            vendor: {
              name: "chunk-vendor",
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
            },
            vue: {
              name: "chunk-vue",
              test: /[\\/]node_modules[\\/]_?vue(.*)/,
              priority: 20,
              reuseExistingChunk: true,
              chunks: "all",
            },

            default: {
              minChunks: 2,
              priority: 30,
              reuseExistingChunk: true,
            },
          },
        },
      };

      Object.assign(config, {
        optimization,
      });
    }
  },
  chainWebpack: (config) => {
    config.output.filename(
      `${process.env.VUE_APP_ASSETS_DIR}/[name].[hash].js`
    );
    config.output.chunkFilename(
      `${process.env.VUE_APP_ASSETS_DIR}/[name].[chunkhash].js`
    );
    config.performance.set("hints", false);
    config.devtool("none");
    config.plugins.delete("prefetch");
    config.plugin("extract-css").tap((arg) => [
      {
        filename: "css/[name].[hash].css",
        chunkFilename: "css/[name].[chunkhash].css",
      },
    ]);
    // 修复HMR
    config.resolve.symlinks(true);
    // 设置内联文件的大小
    config.module
      .rule("images")
      .use("url-loader")
      .loader("url-loader")
      .tap((options) =>
        Object.assign(options, {
          limit: 20 * 1024,
        })
      ); // 20KB

    // 设置别名
    config.resolve.alias.set("components", resolve("src/components"));
    config.resolve.alias.set("assets", resolve("src/assets"));
  },
  css: {
    extract: true,
    requireModuleExtension: true,
    sourceMap: false,
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: {
            // hack: `true; @import "${path.resolve(__dirname, './src/assets/styles/variables.less')}";`
          },
        },
      },
      postcss: {
        plugins: [
          require("autoprefixer")(),
          // 配置根元素fontSize
          require("postcss-pxtorem")({
            rootValue({ file }) {
              // vant 按照375计算，系统UI按照750计算
              return file.indexOf("vant") !== -1 ? 16 : 32;
            },
            propList: ["*"],
          }),
        ],
      },
    },
  },
  devServer: {
    disableHostCheck: true,
    compress: true,
    hot: true,
    open: true,
    port: 8080,
    proxy: {
      "^/gateway": {
        // target: 'http://44.243.251.196:8080', // 马涛本地测试
        // target: 'http://44.243.251.66:8080', // 李凡本地测试
        // target:'223.72.214.88', // pass云地址
        // target: "https://smct-test.fintechabchina.com", // 测试环境地址
        target: 'https://smct.fintechabchina.com', // 生产环境地址
        changeOrigin: true,
        onProxyReq:(proxyReq,req,res)=>{
          proxyReq.removeHeader('referer')
          proxyReq.removeHeader('origin')
          console.log('proxyReq', proxyReq)
          // proxyReq.setHeader('host','devappid.hybrid.alipay-eco.com')
        },
        // autoRewrite: true,
        cookieDomainRewrite: true,
        // pathRewrite: {
        //   '^/': '/'
        // }
      },
      // '/mock': {
      //   target: 'http://localhost:8080', // mockjs
      //   changeOrigin: true,
      //   autoRewrite: true,
      //   cookieDomainRewrite: true
      // }
    },
    before: (app) => {},
  },
};
